package protobuf

import (
	"errors"
	"fmt"
	"gitee.com/sdynasty/clever/codec"
	"gitee.com/sdynasty/clever/codec/protobuf/baseproto"
	"github.com/golang/protobuf/proto"
)

type protobufCodec struct {

}

/**
 * 编码
 */
func (p *protobufCodec) Marshal(router string, msg proto.Message) ([]byte, error) {
	if msg == nil {
		return nil, errors.New("msg is nil")
	}

	pbData, err := proto.Marshal(msg)
	if err != nil {
		return nil, err
	}

	ack :=&baseproto.TransPack{
		Id:    router,
		Data:  pbData,
	}

	ackByte, err := proto.Marshal(ack)
	if err != nil {
		return nil, err
	}
	return ackByte, nil
}

func (p *protobufCodec) Unmarshal(msg []byte) (*codec.MsgPack, error) {
	req := &baseproto.TransPack{}
	err := proto.Unmarshal(msg, req)
	if err != nil {
		return nil, err
	}
	router := req.Id
	dt := codec.GetMessage(router)
	if dt == nil {
		return nil, fmt.Errorf("can`t get message from codec by [%s]", router)
	}
	if req.Data != nil {
		err = proto.Unmarshal(req.Data, dt.(proto.Message))
		if err != nil {
			return nil, err
		}
	}
	msgPack := &codec.MsgPack{
		Router:  router,
		DataPtr: dt,
	}
	return msgPack, nil
}